package entility;



import java.util.List;


public class CheckServerList extends Thread {


	private Machine primaryServer;
	private Machine secondaryServer;

	public CheckServerList(Machine primaryServer, Machine secondaryServer)
	{
		this.primaryServer = primaryServer;
		this.secondaryServer = secondaryServer;
	}


	@Override
	public void run() {
		checkServer();

	}

	private void checkServer() {

		try {
			System.out.println("Verify Server");
			sleep(50000);


		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		Job getServers = new JobImpl(Notification.SERVER);
		getServers.setMethod("getServers");
		try {
			this.primaryServer.getMessage(getServers, 15000);
			checkServer();

		} catch (Exception e) {


			Notification notify = new Notification();
			notify.setMachine(new Machine(this.primaryServer.ip, this.primaryServer.port));
			notify.setType(Notification.SERVER);
			notify.setMessage(Notification.MESSAGEERROR);
			this.primaryServer =secondaryServer;
			
			Job notifyServerFail  = new JobImpl(Notification.SERVER);
			notifyServerFail.setMethod("notify");
			notifyServerFail.setData(notify.getJobData());

			Job updateServersInHost = new JobImpl(Notification.SERVER);
			updateServersInHost.setMethod("update");
			updateServersInHost.setData(secondaryServer);

			Job getHosts = new JobImpl(Notification.SERVER);
			getHosts.setMethod("getHosts");


			try{
				this.primaryServer.getMessage(notifyServerFail);
				List<Machine> hosts = this.primaryServer.getMessage(getHosts).getMachineList();
				for(Machine mac: hosts)
					mac.getMessage(updateServersInHost);

			}catch(Exception e3)
			{
				System.out.println("try again");
			}


		}

	}






}
